package com.woyou.fragment.analysis;

import java.util.ArrayList;
import java.util.List;

import com.jing.biandang.R;
import com.woyou.activity.HomeActivity;
import com.woyou.adapter.CustomerAdapter;
import com.woyou.bean.UserInfo;
import com.woyou.bean.UserReportItem;
import com.woyou.bean.rpc.QueryUserReportListReq;
import com.woyou.bean.rpc.Result;
import com.woyou.component.CustomerChoicePopup;
import com.woyou.component.CustomerChoicePopup.CustomerOrderListener;
import com.woyou.component.CustomerTimePopup;
import com.woyou.component.CustomerTimePopup.CustomerTimeListener;
import com.woyou.component.SuperUI;
import com.woyou.fragment.SuperFragment;
import com.woyou.model.rpc.ShopModel;
import com.woyou.utils.LoginUtils;
import com.woyou.utils.ThreadPoolManager;

import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

/**
 * 顾客分析的界面
 * @author zhou.ni
 *
 */
public class CustomerFragment extends SuperFragment implements OnClickListener {
	private HomeActivity homeActivity;
	private View layout_customer;
	private RelativeLayout layout_customer_time;
	private TextView layout_customer_time_tv;
	private RelativeLayout layout_customer_choice;
	private TextView layout_customer_choice_tv;
	private ListView layout_customer_lv;
	private CustomerAdapter customerAdapter;
	private int customerVisibleLast;
	private CustomerTimePopup customerTimePopup;
	private CustomerChoicePopup customerChoicePopup;

	private QueryUserReportListReq queryUserReportListReq = new QueryUserReportListReq();
	private List<UserReportItem>  userReportList = new ArrayList<UserReportItem>();
	private int pageNext = 1;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		layout_customer = inflater.inflate(R.layout.layout_customer, container, false);
		homeActivity=(HomeActivity)getActivity();
		return layout_customer;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		initView();
		loadData(true);
	}

	/**
	 * 初始化控件
	 */
	public void initView() {
		queryUserReportListReq.setDays("30");			// 设置默认的时间（一个月内消费）
		queryUserReportListReq.setSortType("1");		//设置默认排序方式（下单最多）

		layout_customer_time = (RelativeLayout) layout_customer.findViewById(R.id.layout_customer_time);
		layout_customer_time_tv = (TextView) layout_customer.findViewById(R.id.layout_customer_time_tv);
		layout_customer_choice = (RelativeLayout) layout_customer.findViewById(R.id.layout_customer_choice);
		layout_customer_choice_tv = (TextView) layout_customer.findViewById(R.id.layout_customer_choice_tv);
		layout_customer_lv = (ListView) layout_customer.findViewById(R.id.layout_customer_lv);
		
		customerAdapter = new CustomerAdapter(homeActivity, userReportList);
		layout_customer_lv.setAdapter(customerAdapter);

		layout_customer_time.setOnClickListener(this);
		layout_customer_choice.setOnClickListener(this);
		
		customerChoicePopup = new CustomerChoicePopup(homeActivity, layout_customer_choice, layout_customer_choice_tv);
		customerChoicePopup.setmListener(new CustomerOrderListener() {
			@Override
			public void refreshCustomerOrder(String sortType) {
				queryUserReportListReq.setSortType(sortType);
				pageNext = 1;
				loadData(true);
			}
		});
		customerTimePopup =new CustomerTimePopup(homeActivity, layout_customer_time, layout_customer_time_tv);
		customerTimePopup.setmListener(new CustomerTimeListener() {
			@Override
			public void refreshCustomerTime(String day) {
				queryUserReportListReq.setDays(day);
				pageNext = 1;
				loadData(true);
			}
		});

		layout_customer_lv.setOnScrollListener(new OnScrollListener() {
			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				if (customerVisibleLast == (customerAdapter.getCount() - 1)) {
					loadData(false);
				}
			}

			@Override
			public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
				customerVisibleLast = firstVisibleItem + visibleItemCount - 1;
			}
		});
		
	}

	@Override
	public void onHiddenChanged(boolean hidden) {
		super.onHiddenChanged(hidden);
		if (!hidden) {
			pageNext = 1;
			loadData(true);
		} else {
			if (customerTimePopup != null) {
				customerTimePopup.hidePopup();
			}
			if (customerChoicePopup != null) {
				customerChoicePopup.hidePopup();
			}
		}
	}

	/**
	 * 加载未送出列表数据并且分页 
	 * false 表示不clear原始数据
	 * true  表示先clear原始数据并刷新列表
	 * 
	 * @param isRefresh
	 */
	public void loadData(final boolean clear) {

		ThreadPoolManager.getInstance().executeTask(new Runnable() {
			@Override
			public void run() {
				try {
					homeActivity.showLoadingHint();
					if ( pageNext==0 ) {
						homeActivity.runOnUiThread(new Runnable() {
							@Override
							public void run() {
								SuperUI.openToast(homeActivity, "没有下一页了");
							}
						});
						return;
					}
					UserInfo userInfo = LoginUtils.getUserInfo(homeActivity);
					if ( userInfo!=null ){
						queryUserReportListReq.setsId(userInfo.getsId());
						queryUserReportListReq.setPwd(userInfo.getPwd());
					}
					queryUserReportListReq.setPage(pageNext);
					final Result<List<UserReportItem>> result = ShopModel.getInstance(homeActivity).queryUserReportList(queryUserReportListReq);
					if ( result!=null && result.code==1 ) {
						homeActivity.runOnUiThread(new Runnable() {
							@Override
							public void run() {
								pageNext = result.getPage();
								refreshUI(result, clear);
							}
						});
					} else if( result != null && result.code==-3 ) {
						homeActivity.homeController.exitLogin();
					} else {
						homeActivity.runOnUiThread(new Runnable() {
							@Override
							public void run() {
								SuperUI.openToast(homeActivity, result.getMsg());
							}
						});
					}
				} catch (Exception e) {
					e.printStackTrace();
				} finally {
					homeActivity.hideLoadingHint();
				}
			}
		});
	}
	
	/**
	 * 刷新列表
	 * @param result
	 * @param clear
	 */
	private void refreshUI(Result<List<UserReportItem>> result, boolean clear){
		if ( result==null )
			return;
		
		List<UserReportItem> list = result.getData();
		if ( list==null || list.size()==0 ) {
			SuperUI.openToast(homeActivity, result.getMsg());
		} else {
			if ( clear ) {
				userReportList.clear();
				userReportList.addAll(list);
				customerAdapter.notifyDataSetChanged();
			} else {
				userReportList.addAll(list);
				customerAdapter.notifyDataSetChanged();
			}
		}
		
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.layout_customer_time:
			customerTimePopup.showPopup();
			break;
		case R.id.layout_customer_choice:
			customerChoicePopup.showPopup();
			break;
		}
	}
}
